<template>
    <div>
        <div style="margin: 10px 0">
            <el-input style="width: 200px" placeholder="请输入类别名称" suffix-icon="el-icon-search"
                      v-model="pagequery.cname"></el-input>
            <el-button type="primary" @click="load">搜索</el-button>
            <el-button type="info" @click="reset">重置</el-button>
        </div>
        <div style="margin: 10px 0">
            <el-button type="primary" @click="handleAdd">新增 <i class="el-icon-circle-plus-outline"></i></el-button>
            <el-button type="danger" @click="delBatch">批量删除 <i class="el-icon-remove-outline"></i></el-button>
        </div>
        <el-table @selection-change="handleSelectionChange" :data="tableData" border stripe
                  :header-cell-style="{background:'#eee',color:'#000000'}">
            <el-table-column type="selection" width="168"></el-table-column>
            <el-table-column prop="id" label="ID" width="356"></el-table-column>
            <el-table-column prop="cname" label="类别名称" width="440"></el-table-column>
            <el-table-column label="操作" width="330" align="center">
                <template v-slot:default="scope">
                    <el-button type="success" @click="handleEdit(scope.row)">编辑 <i class="el-icon-edit"></i></el-button>
                    <el-popconfirm
                            class="ml-5"
                            confirm-button-text='确定'
                            cancel-button-text='我再想想'
                            icon="el-icon-info"
                            icon-color="red"
                            title="您确定删除吗？"
                            @confirm="del(scope.row.id)"
                    >
                        <el-button type="danger" slot="reference">删除 <i class="el-icon-remove-outline"></i></el-button>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>
        <div style="padding: 10px 0">
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                           :current-page="pagequery.pageNum" :page-sizes="[5, 10, 20]" :page-size="pagequery.pageSize"
                           layout="total, sizes, prev, pager, next, jumper" :total="total">
            </el-pagination>
        </div>
        <el-dialog title="类别信息" :visible.sync="dialogFormVisible" width="30%">
            <el-form ref="categoryForm" :model="form" :rules="rules" label-width="80px" size="small">
                <el-form-item prop="cname" label="类别名称">
                    <el-input v-model="form.cname" autocomplete="off"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="save">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import qs from "qs";
export default {
    components:{},
    props: {},
    data() {
        return {
            dialogFormVisible: false,
            multipleSelection: [],
            form: {},
            tableData: [],
            total: 0,
            pagequery: {
                pageNum: 1,
                pageSize: 5,
                cname: ""
            },
            rules: {
                cname: [
                    { required: true, message: '请输入类别名称', trigger: 'blur' },
                    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
                ]
            }
        };
    },
     computed: {},
        watch: {},
    methods: {
        handleAdd() {
            this.dialogFormVisible = true;
            this.form = {};
        },
        handleEdit(row) {
            this.form = {...row};
            this.dialogFormVisible = true;
        },
        save() {
            // 检查表单数据中是否包含id，存在id则认为是更新，否则为新增
            if (this.form.id) {
                this.updateCategory(); // 调用更新分类的方法
            } else {
                this.addCategory(); // 调用添加分类的方法
            }
        },
         //新增
        addCategory() {
                this.$refs['categoryForm'].validate((valid) => {
                    if (valid) {
                        this.request.post("/category/add", this.form).then(res => {
                            if (res) {
                                this.$message.success("保存成功")
                                this.dialogFormVisible = false
                                this.load()
                            } else {
                                this.$message.error("保存失败")
                            }
                        })
                    } else {
                        this.$message.error("分类信息请填写完整")
                        return false;
                    }
                });
            },
        // 更新分类
        updateCategory() {
            this.$refs['categoryForm'].validate((valid) => {
                if (valid) {
                    this.request.post("/category/update", this.form).then(res => {
                        if (res) {
                            this.$message.success("分类更新成功");
                            this.dialogFormVisible = false;
                            this.load();
                        } else {
                            this.$message.error("商品更新失败：" + (res.data.message || 'Unknown Error'));
                        }
                    }).catch(error => {
                        this.$message.error("更新请求失败: " + error);
                    });
                } else {
                    this.$message.error("请完整填写分类信息");
                }
            });
        },
            //单个删除
        del(id) {
            this.request.delete("/category/" + id).then(res => {
            // this.request.delete(`/category/${id}`).then(res => {
                    console.log(res)
                    if (res) {
                        this.$message.success("删除成功")
                        this.load()
                    } else {
                        this.$message.error("删除失败")
                    }
            });
        },
        //批量删除
        delBatch() {
            let ids = this.multipleSelection.map(item => item.id);
            if (ids.length === 0) {
                this.$message.warning("请选择要删除的类别");
                return;
            }
            this.request.post("/category/del/batch",  ids ).then(res => {
                if (res) {
                    this.$message.success("批量删除成功");
                    this.load();
                } else {
                    this.$message.error("批量删除失败");
                }
            });
        },
        //重置
        reset() {
            this.pagequery = { pageNum: 1, pageSize: 5, cname: "" };
            this.load();
        },
        //加载数据
        load() {
            this.request.get("/category/page?" + qs.stringify(this.pagequery)).then(res => {
                if (res.code === 200) {
                    this.total = res.data.total;
                    this.tableData = res.data.records;
                     this.tableData.forEach(category=>{
                          console.log(" 分类id: "+category.id+" 分类名称："+category.cname)
                        })
                
                }
        });
        },

        handleSizeChange(pageSize) {
            this.pagequery.pageSize = pageSize;
            this.load();
        },
        handleCurrentChange(pageNum) {
            this.pagequery.pageNum = pageNum;
            this.load();
        },
        handleSelectionChange(val) {
            this.multipleSelection = val;
        }
    },
    created() {
        this.load();
    }
};
</script>
